import childProcess from 'child_process'
import { exec } from 'child_process';
import iconv from 'iconv-lite'
const processes = new Map();

function asyncExecuteCommandExec(command, callback) {
    childProcess.exec(command, (error, stdout, stderr) => {
        if (error) {
            callback(error)
        } else {
            callback(stdout)
        }
    });
}


function asyncExecuteCommand(command, callback) {
    console.log('执行命令:', command);
    
    // 将命令解析为命令名和参数数组
    const [cmd, ...args] = command.split(' ');
    
    const spwanProcess = childProcess.spawn(cmd, args, {
        encoding: 'binary',
        shell: true,
        timeout: 30000
    });
    console.log('pid', spwanProcess.pid)
    const processId = Date.now().toString();
    processes.set(processId, spwanProcess);

    let stdout = '';
    let stderr = '';

    spwanProcess.stdout.on('data', (data) => {
        stdout = iconv.decode(Buffer.from(data, 'binary'), 'gbk');
        callback(stdout)
    });

    spwanProcess.stderr.on('data', (data) => {
        stderr = iconv.decode(Buffer.from(data, 'binary'), 'gbk');
        callback(stderr)
    });

    spwanProcess.on('close', (code) => {
        console.log(`命令执行完成，退出码: ${code}`);
        if (code !== 0) {
            callback(`命令执行失败 (退出码 ${code}):\n${stderr}`);
            return;
        }
        callback(stdout);
    });

    spwanProcess.on('error', (err) => {
        callback(`执行过程出错: ${err.message}`);
    });
}

function StartLog(jsonParam, callback){
    console.log('start log ', jsonParam)
    const param = JSON.parse(jsonParam)
    const target = param.target
    const module = param.moduleName
    const cmd = `hdc -t ${target} shell \"hilog | grep  ${module}\"`
    asyncExecuteCommand(cmd, callback)
}

function StopLogProcess(event){
    console.log('stop log')
    processes.forEach((proc) =>{
        exec(`taskkill /PID ${proc.pid} /T /F`, (error) => {
        if (error) {
            console.error('终止进程失败:', error);
            }
        });
    });
    processes.clear();
    return;
}

function UpdateTargets(callback){
    const intervalId = setInterval(()=>{
        asyncExecuteCommandExec('hdc list targets', callback)
    }, 1500);
    console.log('interval id:', intervalId)
}


export default {
    StartLog,
    StopLogProcess,
    UpdateTargets,
}